import {
  IDCardUtils,
  zoneUtils,
  adapterUtils,
} from "../../../../utils/index.js";
import { STATUS } from "../../../commonConifg.js";
import PROP_DICT from "../dicts/document.js";
import dayjs from "dayjs";

export function documentCommonAdapter(_person) {
  let person = { ..._person };
  person.NOTE = "";

  person.IDNum = IDCardUtils.formatIDNum(person.IDNum);
  person.IDCARD = person.IDNum;
  if (!IDCardUtils.verifyIDNum(person.IDNum)) {
    return adapterUtils.setPersonMessage(person, "身份证号码有误");
  }

  person.BIRTHDATE = IDCardUtils.getBirthday(person.IDNum);
  person.SEX = IDCardUtils.getSex(person.IDNum);
  person.hdAge = IDCardUtils.getAge(person.IDNum);

  // 姓名
  // person.NAME = _person.NAME;

  // 民族
  const race = PROP_DICT.raceArr.find((item) =>
    item.RACENAME.includes(person.txtRACE)
  );
  if (race) {
    person.txtRACE = race.RACENAME;
    person.RACE = race.RACE;
  } else {
    person.txtRACE = "汉";
    person.RACE = "1";
  }

  // 常住类型
  person.RESIDENCETYPE = PROP_DICT.RESIDENCETYPE[person.RESIDENCETYPE] ?? "1";

  // 名册
  if (person.mc) {
    person.chkEt = person.mc.includes("儿") ? "on" : "";
    person.chkYf = person.mc.includes("孕") ? "on" : "";
    person.chkLr = person.mc.includes("老") ? "on" : "";
    person.chkCj = person.mc.includes("残") ? "on" : "";
    person.chkGxy = person.mc.includes("高") ? "on" : "";
    person.chkTnb = person.mc.includes("糖") ? "on" : "";
    person.chkTnb = person.mc.includes("瘤") ? "on" : "";
  } else {
    person.chkYb = "on";
  }

  // 本人联系电话
  person.TELEPHONE = person.txtTel;
  // person.txtTel = _person.brlxdh || "";
  // person.familyPhoneNum = _person.jtlxdh || "";
  // 本人电话多个的时候的值
  // person.hdnTELarr = `01|本人电话|${person.txtTel}；${
  //   person.familyPhoneNum ? `04|家庭电话|${person.familyPhoneNum}；` : ""
  // }`;

  // 联系人电话
  // person.txtcontacttel = person.lxrdh;
  // 联系人姓名
  // person.txtcontactname = person.lxrxm;

  // 工作单位
  // person.UNITNAME = person.gzdw;

  // 户籍地址
  person.HujiAddress$hdnZone = zoneUtils.getLastZoneInfo(
    person.HujiAddress
  ).ZONE;
  if (!person.HujiAddress$hdnZone) {
    return adapterUtils.setPersonMessage(person, "户籍地址识别不到省市区信息");
  }
  // 家庭住址
  person.NowAddress$hdnZone = zoneUtils.getLastZoneInfo(person.NowAddress).ZONE;
  if (!person.NowAddress$hdnZone) {
    return adapterUtils.setPersonMessage(person, "居住地址识别不到省市区信息");
  }

  // 户籍类别
  person.REGISTERTYPE = PROP_DICT.REGISTERTYPE[person.REGISTERTYPE] ?? "0";

  // 建档人姓名
  // person.CreatePerson = person.jdrxm;

  // 建档日期
  person.BUILDDATE = adapterUtils.formattedDate(person.BUILDDATE, true);
  // 责任医生
  // person.DutyDoctor = person.zrys;
  // 血型
  person.ABOBLOOD = PROP_DICT.ABOBLOOD[person.ABOBLOOD];
  // RH血型
  person.RHBLOOD = PROP_DICT.RHBLOOD[person.RHBLOOD];
  // 文化程度
  person.EDUC = PROP_DICT.EDUC[person.EDUC];
  // 职业
  person.OCCUATION = PROP_DICT.OCCUATION[person.OCCUATION];
  // 婚姻
  person.MARI = PROP_DICT.MARI[person.MARI];
  // 医疗费用支付方式
  person.INSURANCETYPE1 = person.INSURANCETYPE.includes("城镇职工基本医疗保险")
    ? "1"
    : "";
  person.INSURANCETYPE2 = person.INSURANCETYPE.includes("城镇居民基本医疗保险")
    ? "2"
    : "";
  person.INSURANCETYPE3 = person.INSURANCETYPE.includes("新型农村合作医疗")
    ? "3"
    : "";
  person.INSURANCETYPE4 = person.INSURANCETYPE.includes("贫困救助") ? "4" : "";
  person.INSURANCETYPE5 = person.INSURANCETYPE.includes("商业医疗保险")
    ? "5"
    : "";
  person.INSURANCETYPE6 = person.INSURANCETYPE.includes("全公费") ? "6" : "";
  person.INSURANCETYPE7 = person.INSURANCETYPE.includes("全自费") ? "7" : "";
  person.INSURANCETYPE8 = person.INSURANCETYPE.includes("其他") ? "8" : "";
  // 过敏药物
  // person.hdnGMS = formatGMS(person.gmyw);
  // 暴露史
  // 疾病
  person.hdnJBS = getFormattedJBS(person, person.hdnJBS);
  // 手术
  // person.hdnSSS = getFormattedXXS(person.ss, 2);
  // person.rbtnlistss = person.hdnSSS ? "0" : "1"; // 0: 有, 1: 无
  // 外伤
  // person.hdnWSS = getFormattedXXS(person.ws, 3);
  // person.rbtnlistws = person.hdnWSS ? "0" : "1"; // 0: 有, 1: 无
  // 输血
  // person.hdnSXS = getFormattedXXS(person.sx, 4);
  // person.rbtnlistsx = person.hdnSXS ? "0" : "1"; // 0: 有, 1: 无
  // 家族史
  person = formatJzs(person, "fq");
  person = formatJzs(person, "mq");
  person = formatJzs(person, "xdjm");
  person = formatJzs(person, "zn");
  // person.zn1 = person.jzs.includes("无此关系") ? "12" : "1";
  // person.znother = person.jzs.includes("无此关系") ? "无此关系" : "";
  // 残疾情况
  // person.hdnCJS = getFormattedCJS(person.cjqk);
  // 厨房排风设施
  person.AIRINESS = PROP_DICT.AIRINESS[person.AIRINESS] || "2";
  // 燃料类型
  person.FULE = PROP_DICT.FULE[person.FULE] || "1";
  // 饮水
  person.DRINKINGWATER = PROP_DICT.DRINKINGWATER[person.DRINKINGWATER] || "1";
  // 厕所
  person.TOILET = PROP_DICT.TOILET[person.TOILET] || "1";
  // 禽畜栏
  person.LIVESTOCK = PROP_DICT.LIVESTOCK[person.LIVESTOCK] || "0";

  // 现住址
  person.REGADDRESS = _person.NowAddress;
  // 户籍地址
  person.HujiAddressZone = _person.HujiAddress;
  person.RPRADDRESS = _person.HujiAddress;
  person.txtNowMenpai = _person.HujiAddress;
  // person.jtzz = CONFIG.DIS_ADDRESS + _person.jtzz;
  // person.jtzzLastCode = zoneUtils.getLastZoneInfo(CONFIG.ADDRESS + _person.jtzz).ZONE;
  // person.hjdzLastCode = zoneUtils.getLastZoneInfo(person.hjdz).ZONE;

  person.fq = "";
  // person.hdnJBS = "";
  person.hdnBLS = "";
  person.hdnGMS = "";
  person.mq = "";
  person.xdjm = "";
  person.zn = "";
  return person;
}

function formatGMS(gms) {
  let gmsArr = gms.split(/,|，/g);
  let str = "";
  if (gmsArr.includes("青霉素")) {
    str += "qms,1,青霉素+；";
  }
  if (gmsArr.includes("磺胺")) {
    str += "ha,2,磺胺+；";
  }
  if (gmsArr.includes("链霉素")) {
    str += "lms,3,链霉素+；";
  }
  gmsArr = gmsArr.filter(
    (item) => !["青霉素", "磺胺", "链霉素"].includes(item)
  );
  if (gmsArr.length) {
    str += gmsArr.join();
  }
  return str;
}

function getFormattedJBS(person, jbs = "") {
  const arr = [
    "2 高血压",
    "3 2型糖尿病",
    "4 冠心病",
    "5 慢性阻塞性肺疾病",
    "6 恶性肿瘤",
    "7 脑卒中",
    "8 重性精神疾病",
    "9 结核病",
    "10 肝炎",
    "11 其他法定传染病",
    "12 职业病",
  ];
  const nameArr = jbs
    .split(/,|，/g)
    .map((jb) => arr.find((item) => item.includes(jb)))
    .filter((item) => item);

  let str = "";
  let num = 1;
  for (const name of nameArr) {
    str += `${name},`;
    switch (name) {
      case "2 高血压":
        str += `${formatDate(person, "gxy")},`;
        str += "gxy,2；";
        break;
      case "3 2型糖尿病":
        str += `${formatDate(person, "tnb")},`;
        str += "tnb,3；";
        break;
      case "4 冠心病":
        str += `${formatDate(person, "gxb")},`;
        str += "gxb,4；";
        break;
      case "5 慢性阻塞性肺疾病":
        str += `${formatDate(person, "mxzsfb")},`;
        str += "mxzsfb,5；";
        break;
      case "6 恶性肿瘤":
        str += `${formatDate(person, "exzl")},`;
        str += "exzl,6；";
        break;
      case "7 脑卒中":
        str += `${formatDate(person, "ncz")},`;
        str += "ncz,7；";
        break;
      case "8 重性精神疾病":
        str += `${formatDate(person, "zxjsb")},`;
        str += "zxjsb,8；";
        break;
      case "9 结核病":
        str += `${formatDate(person, "jhb")},`;
        str += "jhb,9；";
        break;
      case "10 肝炎":
        str += `${formatDate(person, "gy")},`;
        str += "gy,10；";
        break;
      case "11 其他法定传染病":
        str += `${formatDate(person, "qtcrb")},`;
        str += "qtcrb,11；";
        break;
      case "12 职业病":
        str += `${formatDate(person, "zyb")},`;
        str += "zyb,12；";
        break;
      default:
        // str += `qtb${num > 1 ? num : ""},${num + 12}；`;
        // num++;
        break;
    }
  }

  return str;
}

function formatDate(person, illName) {
  return adapterUtils.formattedDate(person[`time_${illName}`]);
}

// 家族史
function formatJzs(person, relation) {
  const jzsArr = [
    "无",
    "高血压",
    "2型糖尿病",
    "冠心病",
    "慢性阻塞性肺疾病",
    "恶性肿瘤",
    "脑卒中",
    "重性精神疾病",
    "结核病",
    "肝炎",
    "先天畸形",
    "其他",
  ];

  const other = [];
  const illIndexSet = new Set();
  person[relation].split(/,|，/).forEach((ill, index) => {
    if (~jzsArr.findIndex((item) => item.includes(ill))) {
      illIndexSet.add(index + 1);
    } else {
      illIndexSet.add(12);
      other.push(ill);
    }
  });
  const res = {};
  [...illIndexSet].sort().forEach((illIndex, index) => {
    res[`${relation}${index + 1}`] = illIndex;
  });
  res[`${relation}other`] = other.join("，");
  return { ...person, ...res };
}

function getFormattedCJS(cjs) {
  let str = "";
  if (!cjs || cjs === "无") return str;
  const cjsArr = cjs.split(/,|，/g);
  cjsArr.forEach((item) => {
    switch (item) {
      case "视力残疾":
        str += "slcj,2,";
        break;
      case "听力残疾":
        str += "tlcj,3,";
        break;
      case "语言残疾":
        str += "yycj,4,";
        break;
      case "肢体残疾":
        str += "ztcj,5,";
        break;
      case "智力残疾":
        str += "zlcj,6,";
        break;
      case "精神残疾":
        str += "jscj,7,";
        break;
      default:
        str += "qtcj,8,";
        break;
    }
    str += `${item}++；`;
  });
  return str;
}

/**
 * 获取XX史的格式化数组
 * @param str
 * @returns [{name, date}, ...]
 */
function getXXSArr(str) {
  const arr = str.match(/\d?\s?.*? 日期：\d{4}-\d{2}-\d{2}/g) || [];
  const formattedArr = arr.reduce((pre, cur) => {
    const [name, date] = cur.trim().split(" 日期：");
    pre.push({ name, date });
    return pre;
  }, []);

  return formattedArr;
}

function getFormattedXXS(xxs, type) {
  const formattedArr = getXXSArr(xxs);
  let str = "";
  for (const { name, date } of formattedArr) {
    str += `${name},${date},${type === 2 ? "undefined," : ""}${type}；`;
  }
  return str;
}
